package com.ucs.ui;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

/**
 * SimpleActivity is a subclass of Activity that makes it trivial to create a sub-Activity, and handle it's
 * results (ok or cancel). No need to deal with requestCodes, since this class handles creating correlationIds
 * automatically.
 *
 */
public class SimpleActivity extends Activity {
    private static final String TAG = "ucs";

	private static final Random rand = new Random();
	protected static final Map<Integer, ResultCallbackIF> _callbackMap = new HashMap<Integer, ResultCallbackIF>();

	/** use this method to launch the sub-Activity, and provide a functor to handle the 
	 * result - ok or cancel 
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void launchSubActivity(Class subActivityClass, ResultCallbackIF callback, Bundle extras) {
		Intent i = new Intent(this, subActivityClass);
		if (extras != null){
			i.putExtras(extras);
		}
		int correlationId = rand.nextInt(20000000);

		_callbackMap.put(correlationId, callback);
		Log.d(TAG, "SimpleActivity:launchSubActivity:_callbackMap="+_callbackMap);

		startActivityForResult(i, correlationId);
	}

	@Override
	protected void onActivityResult(int correlationId, int resultCode, Intent intent) {
		Log.d(TAG, "SimpleActivity:onActivityResult:correlationId="+correlationId);
		Log.d(TAG, "_callbackMap="+_callbackMap);
		ResultCallbackIF callback = _callbackMap.get(correlationId);
		if (callback == null) {
			Log.d("ucs", "callback==null");
			return;
		}
		try {
			switch (resultCode) {
				case Activity.RESULT_CANCELED:
					Log.d(TAG, "SimpleActivity:onActivityResult:resultCode=RESULT_CANCELED");
					callback.resultCancel(intent);
					_callbackMap.remove(correlationId);
					break;
				case Activity.RESULT_OK:
					Log.d(TAG, "SimpleActivity:onActivityResult:resultCode=RESULT_OK");
					callback.resultOk(intent);
					_callbackMap.remove(correlationId);
					break;
				default:
					Log.e(TAG, "Couldn't find callback handler for correlationId");
			}
		}
		catch (Exception e) {
			Log.e(TAG, "Problem processing result from sub-activity", e);
		}
	}

	/**
	 * ResultCallbackIF is a simple interface that you have to implement to handle results - ok or cancel from a
	 * sub-Activity.
	 *
	 */
	public static interface ResultCallbackIF {
	
	  public void resultOk(Intent intent);
	  public void resultCancel(Intent intent);
	
	}
}
